<?php

namespace App\Kuafu\Pay\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Model\Traits\KfUid;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class ShopPaymentModel extends BaseModel
{
    use HasFactory, KfSoftDeletes, KfUid;

    protected $connection       = 'mysql';
    protected $table            = 'shop_payments';
    protected $primaryKey       = 'id';

    protected $fillable = [
        'shopId',
        'paymentName',
        'payChannel',
        'isOpen',
        'payConfig',
        'sort',
        'isDeleted',
        'createdByUid',
        'updatedByUid'
    ];

    /**
     * 新增、更新数据
     * @param int $shopId
     * @param string $paymentName
     * @param int $payChannel
     * @param string $payConfig
     * @param int $sort
     * @param int $isOpen
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     */
    public static function addData(
        int $shopId,
        string $paymentName,
        int $payChannel,
        string $payConfig,
        int $sort,
        int $isOpen
    ) {
        return self::query()->updateOrCreate(['shopId' => $shopId, 'payChannel' => $payChannel],
            ['paymentName' => $paymentName, 'isOpen' => $isOpen, 'payConfig' => $payConfig, 'sort' => $sort]);
    }

    /**
     * 获取支付配置
     * 缓存在ShopPayService::getPayConfigCache中调用
     * @param int $shopId
     * @param int $payChannel
     * @return array
     */
    public static function getPayConfig(int $shopId, int $payChannel): array
    {
        $configStr = self::query()
                         ->where('shopId', $shopId)
                         ->where('payChannel', $payChannel)
                         ->value('payConfig');

        if (!$configStr) {
            return [];
        }

        return json_decode($configStr, true);
    }

    /**
     * 关闭
     * 使用ShopPayService::sClose调用
     * @param int $shopId
     * @param int $payChannel
     * @return int
     */
    public static function close(int $shopId, int $payChannel): int
    {
        return self::query()
                   ->where('shopId', $shopId)
                   ->where('payChannel', $payChannel)
                   ->update(['isOpen' => 0]);
    }
}
